<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Content_model extends MY_Model {

    function __construct() {
        parent::__construct("content", "id", Array(
            "thumbnail_img" => "Image_model",
            "banner_img" => "Image_model",
            "poster_id" => "User_model"
        ));
    }

    protected function read($where = Array(), $fetchForeign = false, $depth = 1, $page = -1, $limit = 10) {
        $results = parent::read($where, $fetchForeign, $depth, $page, $limit);

        foreach ($results as $result) {
            $postedArr = explode(" ", $result->posted);
            $result->posted_date = $postedArr[0];
            $result->posted_time = $postedArr[1];
            $pics = Array();
            $this->load->model("Image_model");
            $this->db->from("content_pics")->where("content_id", $result->id);
            foreach ($this->db->get()->result() as $row) {
                $imgId = $row->image_id;
                $image = $this->Image_model->findById($imgId);
                if ($image != NULL) {
                    array_push($pics, $image);
                }
            }
            $result->pics = $pics;            
        }

        return $results;
    }

    public function create($title, $text, $thumbId, $bannerId, $userId = false, $tags = Array(), $pics = Array()) {
        // generate attr
        $posted = date("Y-m-d H:i:s");
        $posterId = (($userId == false) ? $this->curUserId() : $userId);
        if ($posterId < 0) {
            return $posterId;
        }
        $tagString = "";
        $i = 0;
        foreach ($tags as $tag) {
            $tagString .= $tag;
            if ($i < count($tags) - 1) {
                $tagString .= ",";
            }
            $i++;
        }
        
        $contId = parent::create(Array(
                    "title" => $title,
                    "text" => $text,
                    "posted" => $posted,
                    "poster_id" => $posterId,
                    "tags" => $tagString,
                    "thumbnail_img" => $thumbId,
                    "banner_img" => $bannerId
        ));

        foreach ($pics as $picId) {
            $this->load->model("Image_model");

            $data = array(
                'content_id' => $contId,
                'image_id' => $picId,
            );
            $this->db->insert("content_pics", $data);
        }

        return $contId;
    }

}